// src/store/slices/uiSlice.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface Modal {
  id: string;
  type: string;
  data?: any;
}

interface Toast {
  id: string;
  type: 'success' | 'error' | 'info' | 'warning';
  title: string;
  message?: string;
  duration?: number;
}

interface UIState {
  // 加载状态
  isGlobalLoading: boolean;
  loadingMessage: string | null;

  // 模态框
  modals: Modal[];
  activeModal: Modal | null;

  // Toast消息
  toasts: Toast[];

  // 导航
  currentScreen: string;
  previousScreen: string | null;
  navigationStack: string[];

  // 底部Tab
  activeTab: string;
  tabBadges: Record<string, number>;

  // 搜索
  searchQuery: string;
  searchHistory: string[];
  isSearching: boolean;

  // 刷新
  isRefreshing: Record<string, boolean>;

  // 键盘
  isKeyboardVisible: boolean;
  keyboardHeight: number;

  // 网络
  isOnline: boolean;
  connectionType: string | null;

  // 界面状态
  isDarkMode: boolean;
  orientation: 'portrait' | 'landscape';
  screenDimensions: {
    width: number;
    height: number;
  };

  // 滚动位置记录
  scrollPositions: Record<string, number>;

  // 展开/折叠状态
  expandedItems: Record<string, boolean>;
}

const initialState: UIState = {
  isGlobalLoading: false,
  loadingMessage: null,

  modals: [],
  activeModal: null,

  toasts: [],

  currentScreen: 'Home',
  previousScreen: null,
  navigationStack: ['Home'],

  activeTab: 'Home',
  tabBadges: {},

  searchQuery: '',
  searchHistory: [],
  isSearching: false,

  isRefreshing: {},

  isKeyboardVisible: false,
  keyboardHeight: 0,

  isOnline: true,
  connectionType: 'wifi',

  isDarkMode: false,
  orientation: 'portrait',
  screenDimensions: {
    width: 375,
    height: 812,
  },

  scrollPositions: {},
  expandedItems: {},
};

const uiSlice = createSlice({
  name: 'ui',
  initialState,
  reducers: {
    // 加载状态
    setGlobalLoading: (
      state,
      action: PayloadAction<{ isLoading: boolean; message?: string }>
    ) => {
      state.isGlobalLoading = action.payload.isLoading;
      state.loadingMessage = action.payload.message || null;
    },

    // 模态框
    openModal: (state, action: PayloadAction<Modal>) => {
      state.modals.push(action.payload);
      state.activeModal = action.payload;
    },

    closeModal: (state, action: PayloadAction<string>) => {
      state.modals = state.modals.filter((m) => m.id !== action.payload);
      state.activeModal = state.modals[state.modals.length - 1] || null;
    },

    closeAllModals: (state) => {
      state.modals = [];
      state.activeModal = null;
    },

    // Toast消息
    showToast: (state, action: PayloadAction<Toast>) => {
      state.toasts.push(action.payload);

      // 限制toast数量
      if (state.toasts.length > 5) {
        state.toasts.shift();
      }
    },

    removeToast: (state, action: PayloadAction<string>) => {
      state.toasts = state.toasts.filter((t) => t.id !== action.payload);
    },

    clearToasts: (state) => {
      state.toasts = [];
    },

    // 导航
    setCurrentScreen: (state, action: PayloadAction<string>) => {
      state.previousScreen = state.currentScreen;
      state.currentScreen = action.payload;

      // 更新导航栈
      state.navigationStack.push(action.payload);
      if (state.navigationStack.length > 10) {
        state.navigationStack.shift();
      }
    },

    // Tab
    setActiveTab: (state, action: PayloadAction<string>) => {
      state.activeTab = action.payload;
    },

    setTabBadge: (
      state,
      action: PayloadAction<{ tab: string; count: number }>
    ) => {
      if (action.payload.count > 0) {
        state.tabBadges[action.payload.tab] = action.payload.count;
      } else {
        delete state.tabBadges[action.payload.tab];
      }
    },

    // 搜索
    setSearchQuery: (state, action: PayloadAction<string>) => {
      state.searchQuery = action.payload;
    },

    addSearchHistory: (state, action: PayloadAction<string>) => {
      if (!state.searchHistory.includes(action.payload)) {
        state.searchHistory.unshift(action.payload);
        if (state.searchHistory.length > 20) {
          state.searchHistory.pop();
        }
      }
    },

    clearSearchHistory: (state) => {
      state.searchHistory = [];
    },

    setIsSearching: (state, action: PayloadAction<boolean>) => {
      state.isSearching = action.payload;
    },

    // 刷新
    setRefreshing: (
      state,
      action: PayloadAction<{ key: string; isRefreshing: boolean }>
    ) => {
      state.isRefreshing[action.payload.key] = action.payload.isRefreshing;
    },

    // 键盘
    setKeyboardState: (
      state,
      action: PayloadAction<{ isVisible: boolean; height?: number }>
    ) => {
      state.isKeyboardVisible = action.payload.isVisible;
      state.keyboardHeight = action.payload.height || 0;
    },

    // 网络
    setNetworkState: (
      state,
      action: PayloadAction<{ isOnline: boolean; connectionType?: string }>
    ) => {
      state.isOnline = action.payload.isOnline;
      state.connectionType = action.payload.connectionType || null;
    },

    // 界面
    toggleDarkMode: (state) => {
      state.isDarkMode = !state.isDarkMode;
    },

    setOrientation: (state, action: PayloadAction<'portrait' | 'landscape'>) => {
      state.orientation = action.payload;
    },

    setScreenDimensions: (
      state,
      action: PayloadAction<{ width: number; height: number }>
    ) => {
      state.screenDimensions = action.payload;
    },

    // 滚动位置
    saveScrollPosition: (
      state,
      action: PayloadAction<{ key: string; position: number }>
    ) => {
      state.scrollPositions[action.payload.key] = action.payload.position;
    },

    // 展开/折叠
    toggleExpandedItem: (state, action: PayloadAction<string>) => {
      state.expandedItems[action.payload] = !state.expandedItems[action.payload];
    },

    setExpandedItem: (
      state,
      action: PayloadAction<{ key: string; expanded: boolean }>
    ) => {
      state.expandedItems[action.payload.key] = action.payload.expanded;
    },

    resetUI: () => initialState,
  },
});

export const {
  setGlobalLoading,
  openModal,
  closeModal,
  closeAllModals,
  showToast,
  removeToast,
  clearToasts,
  setCurrentScreen,
  setActiveTab,
  setTabBadge,
  setSearchQuery,
  addSearchHistory,
  clearSearchHistory,
  setIsSearching,
  setRefreshing,
  setKeyboardState,
  setNetworkState,
  toggleDarkMode,
  setOrientation,
  setScreenDimensions,
  saveScrollPosition,
  toggleExpandedItem,
  setExpandedItem,
  resetUI,
} = uiSlice.actions;

export default uiSlice.reducer;